<?php

namespace app\yperp\logic\yp;

use app\yperp\common\GuzzleHttp;
use GuzzleHttp\Client;
use think\facade\Cache;

class YpLogin
{

    private static $instance;
    public static function getInstance()
    {
        if (static::$instance === null) {
            static::$instance = new static();
        }
        return static::$instance;
    }
    /**
     * 虹创登录密码加解密
     * @param string $string
     * @param string $key
     * @return string
     */
    static function secret($string, $key = '46cc793c53dc451b', $operation = false)
    {
        if ($operation) {
            return openssl_decrypt(base64_decode($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        }
        return base64_encode(openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA));
    }
    /**
     * 下载验证码图片并保存
     */
    function getImage($microtime, $savePath)
    {
        //使用GuzzleHttp的get方法下载图片并保存

        // 图片的远程URL
        $imgUrl = 'https://yp.changhong.com/platform-frame-web-admin/verify/image?verifyId=' . $microtime;


        // 创建一个新的Guzzle HTTP客户端实例
        $client = new Client([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);

        // 发起GET请求以获取图片资源
        try {
            $response = $client->get($imgUrl, ['sink' => $savePath]);

            // 检查HTTP响应状态码是否为成功（例如200 OK）
            if ($response->getStatusCode() == 200) {
                // 获取响应体作为流对象
                $body = $response->getBody();

                // 将流对象的内容保存到本地文件
                $body->rewind(); // 回到流的开始位置
                file_put_contents($savePath, $body->getContents());
                return $savePath;
                // echo "验证码成功下载";
            } else {
                return false;
                // echo "无法下载图片，响应状态码: " . $response->getStatusCode();
            }
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
            // 处理请求过程中的任何错误
            // echo "下载图片时发生错误: " . $e->getMessage();
        }
    }
    /**
     * 调用OCR接口
     */
    function ocrApi($microtime, $apiUrl = 'http://ocrapi.jzzw-tech.cn/ocr')
    {
        $imgPath = env('root_path') . 'runtime/yp_login_code_image.png';
        $imgPath = $this->getImage($microtime, $imgPath);
        // 初始化cURL会话
        $ch = curl_init();

        // 设置cURL选项
        curl_setopt_array($ch, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => ['image' => new \CurlFile($imgPath)],
            CURLOPT_HTTPHEADER => ['Content-Type: multipart/form-data'],
        ]);

        // 执行cURL请求
        $response = curl_exec($ch);

        // 检查cURL错误
        if (curl_errno($ch)) {
            throw new \Exception('cURL error: ' . curl_error($ch));
        }

        // 获取HTTP响应状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭cURL会话
        curl_close($ch);

        // 根据HTTP响应状态码处理结果
        if ($httpCode !== 200) {
            throw new \Exception('Failed to upload image. Server responded with status code: ' . $httpCode);
        }

        // 返回响应内容
        $code = json_decode($response, true);
        return $code['text'];
    }
    /**
     * 登录
     */
    function login($user = 'csmb', $password = 'hcyp1234!', $new = false)
    {
        $token = Cache::get('yp_login_token');
        $isLogin = false;
        if (!$token || $new == true) {
            while (!$isLogin) {

                $url = 'https://yp.changhong.com/platform-frame-web-admin/api/oauth/login';
                $microtime = microtime();
                $res = GuzzleHttp::post($url, [
                    'json' => [
                        "userAccount" => $user,
                        "password" => $this->secret($password),
                        "code" => $this->ocrApi($microtime),
                        "verifyId" => $microtime
                    ]
                ]);

                if (isset($res['body']['token'])) {
                    $paload_array = $this->jwt_to_array($res['body']['token']);
                    $expire = $paload_array['exp'] - $paload_array['iat'];
                    Cache::set('yp_login_token', $res['body']['token'], $expire);
                    $token = $res['body']['token'];
                    $isLogin = true;
                    // dump($res['body']['token']); 
                    // dump('登录成功'); 
                    // return $token;
                } else {
                    // dump('登录失败');
                    sleep(1);
                }

            }
        } else {
            $isLogin = true;
        }
        return $token;
    }

    function jwt_to_array($jwtToken)
    {
        // 分割JWT的三个部分
        $parts = explode('.', $jwtToken);

        // 验证是否有三个部分（Header.Payload.Signature）
        if (count($parts) !== 3) {
            throw new \InvalidArgumentException('Invalid JWT token');
        }

        // 解码Payload部分为JSON格式
        $payload = json_decode(base64_decode(strtr($parts[1], '-_', '+/')), true);

        return $payload;
    }

    function checkLogin()
    {
        if ($this->login()) {
            return true;
        } else {
            return false;
        }
    }
}
